package org.wjw.utils;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

//封装成一个单例模式
public class DBUtil {
    //声明数据源对象
    private static volatile DataSource dataSource = null;
    //定义连接参数
    private static final String URL = "jdbc:mysql://localhost:3306/blog_db?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false&characterEncoding=utf8";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";

    //获取数据库连接对象
    public static Connection getConnection() throws SQLException {
        if (dataSource == null) {
            //在多线程中可能会出现创建多个对象的情况
            //所以需要加锁,使用DBUtil.class作为锁对象,JVM中全局唯一
            synchronized (DBUtil.class) {
                if (dataSource == null) {
                    MysqlDataSource mysqlDataSource = new MysqlDataSource();
                    mysqlDataSource.setURL(URL);
                    mysqlDataSource.setUser(USER);
                    mysqlDataSource.setPassword(PASSWORD);
                    dataSource = mysqlDataSource;
                }
            }
        }
        return dataSource.getConnection();
    }

    //对外提供一个私有的构造方法
    private DBUtil() {
    }

    public static void close(ResultSet resultSet, Statement statement, Connection connection) {
        //依次关闭
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }


    }

}
